package com.dhecp.project.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.project.system.domain.SysUserAndRoleJurisdiction;
import com.dhecp.project.system.service.SysUserAndRoleJurisdictionService;

/**
 * 权限设置 控制层
 * @author DH-Xxj
 * @version 2019年10月28日
 */

@Controller
@RequestMapping("/system/userandrolejurisdiction")
public class SysUserAndRoleJurisdictionController extends BaseController {
//    private String prefix = "system/userandrolejurisdiction";
    private String moduleTable = ModuleTable.USER_AND_ROLE_JURISDICTION;

    @Autowired
    private SysUserAndRoleJurisdictionService userAndRoleJurisdictionService;

    
    /**
     * 打开用户选择列表，简单用户信息，用于选择用户
     * @param vUsers 原本已指定的用户（格式为：[1001],[1002]），若不为空，则在用户选择列表中默认为选中状态。 
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/userselect")
    public ModelAndView userInfoSelectList(@RequestParam Map<String, Object> params){
//    	params.put("vUsers", "[1001],[1002],[admin]");
        ModelAndView mv = this.getModelAndView();
    	String pagetype = "checkbox";
    	String[] vUsersList = null;
    	if (params.get("vUsers") != null && params.get("vUsers") != ""){ //若vUsers存在，则转为数组形式。
    		try{
        		String vUsers = params.get("vUsers").toString();
        		String vUsersSub = vUsers.substring(1, vUsers.length()-1);
        		vUsersList = vUsersSub.split("\\],\\[");
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	mv.addObject("pagetype", pagetype);	//页面类型为多选
    	mv.addObject("vUsersList", vUsersList);	//原本已指定的用户,数组中存在的用户在列表中默认为选中状态
        mv.setViewName("system/user/user_select");
        return mv;
    }
    
    /**
     * 打开组织机构选择树，用于选择机构
     * @param vOrgs 原本已指定的机构（格式为：[C101.D101],[C101.D103]），若不为空，则在机构选择树中默认为选中状态。 
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:organization:view")
    @GetMapping("/orgselect")
    public ModelAndView organizationSelectTree(@RequestParam Map<String, Object> params){
//    	params.put("vOrgs", "[C101.D101],[C101.D103]");
        ModelAndView mv = this.getModelAndView();
        String vOrgs = "";
//        String[] vOrgsList = null;
    	if (params.get("vOrgs") != null && params.get("vOrgs") != ""){ //若vOrgs存在，则转为数组形式。
    		vOrgs = params.get("vOrgs").toString();
//    		try{
//        		vOrgs = params.get("vOrgs").toString();
//        		String vOrgsSub = vOrgs.substring(1, vOrgs.length()-1);
//        		vOrgsList = vOrgsSub.split("\\],\\[");
//    		}catch(Exception e){
//    			e.printStackTrace();
//    		}
    	}
    	mv.addObject("vOrgs", vOrgs);	//原本已指定的机构,在树中默认为选中状态
        mv.setViewName("system/organization/organization_select");
        return mv;
    }
    
    /**
     * 查询指定菜单下的功能及相应权限
     * @param vType 必要参数：权限类型， role:角色权限分配,user:用户权限分配
     * @param pid 必要参数：vType=role时为角色 guid号的值，vType=user时为用户编号 userId的值
     * @param searchModule 或 menuGuid 或 menuPguid 具体功能或所属菜单或所属菜单上级 guid 三选一
     * @return TableDataInfo
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:userandrolejurisdiction:list")
    @RequiresPermissions(value={"system:user:list","system:role:list"},logical=Logical.OR)
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
    	if (params.get("vType") == null || params.get("vType") == ""){
    		return getDataTable("必要参数：权限类型[vType]为可空，其值为: role:角色权限分配,user:用户权限分配。");   
    	}
    	params.put("moduleTable", moduleTable);
        List<SysUserAndRoleJurisdiction> list = new ArrayList<SysUserAndRoleJurisdiction>();
        try {
            if ("role".equals(params.get("vType").toString())){
            	list = userAndRoleJurisdictionService.queryUserAndRoleJurisdictionListForRole(params);
            }else if ("user".equals(params.get("vType").toString())){
            	list = userAndRoleJurisdictionService.queryUserAndRoleJurisdictionListForUser(params);
            }else{
            	return getDataTable("权限类型有误，可选类型为： role（角色权限分配）,user（用户权限分配）。"); 
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(list);
    }

    /**
     * 保存功能权限
     * @param infoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:userandrolejurisdiction:edit")
    @RequiresPermissions(value={"system:user:edit","system:role:edit"},logical=Logical.OR)
    @Log(title = "保存功能权限", businessType = BusinessType.UPDATE)
    @PostMapping("/formoduleeditpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userAndRoleJurisdictionForModuleEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("infoItems") == null || params.get("infoItems") == ""){
        	return AjaxResult.error("缺少参数infoItems【对应实体类的json格式字符串】。");
        }
        params.put("upType", "formodule");
        try {
            ajaxResult= userAndRoleJurisdictionService.updateUserAndRoleJurisdiction(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 保存数据权限
     * @param infoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:userandrolejurisdiction:edit")
    @RequiresPermissions(value={"system:user:edit","system:role:edit"},logical=Logical.OR)
    @Log(title = "保存功能权限", businessType = BusinessType.UPDATE)
    @PostMapping("/fordataeditpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userAndRoleJurisdictionForDataEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("infoItems") == null || params.get("infoItems") == ""){
        	return AjaxResult.error("缺少参数infoItems【对应实体类的json格式字符串】。");
        }
        params.put("upType", "fordata");
        try {
            ajaxResult= userAndRoleJurisdictionService.updateUserAndRoleJurisdiction(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
}
